using System.Drawing;
using DjVu;
using ImageFormat = System.Drawing.Imaging.ImageFormat;

namespace ImageSaver
{
    public class Saver
    {
        private static volatile Saver _instance;
        private static object _syncRoot = new object();

        private Saver() 
        {
        }

        public static Saver GetInstance()
        {
            if (_instance == null)
            {
                lock (_syncRoot)
                {
                    if (_instance == null)
                        _instance = new Saver();
                }
            }
            return _instance;
        }

        public void Save(string filepath, string extension, Bitmap bitmap)
        {
            switch (extension)
            {
                case "bmp":
                    {
                        bitmap.Save(filepath, ImageFormat.Bmp);
                        break;
                    }
                case "jpg":
                    {
                        bitmap.Save(filepath, ImageFormat.Jpeg);
                        break;
                    }
                case "png":
                    {
                        bitmap.Save(filepath, ImageFormat.Png);
                        break;
                    }
                case "psd":
                    {
                        var auBitmap = new Aurigma.GraphicsMill.Bitmap(bitmap);
                        auBitmap.Save(filepath);
                        break;
                    }
                case "djvu":
                    {
                        SaveToAdditionalFormats(filepath, bitmap, 0);
                        break;
                    }
                case "pdf":
                    {
                        SaveToAdditionalFormats(filepath, bitmap, 1);
                        break;
                    }
            }
        }

        private void SaveToAdditionalFormats(string filepath, Image bitmap, byte extension)
        {
            using (var enc = new Encoder(new EncoderParams("scan300")))
            {
                enc.AddPages(bitmap);
                using (var doc = enc.GetEncodedDocument())
                {
                    switch (extension)
                    {
                        case 0:
                            doc.SaveAs(filepath);
                            break;
                        case 1:
                            doc.SaveAs(filepath, DocumentType.PDF);
                            break;
                    }
                }
            }
        }
    }
}